using System;
using System.Collections.Generic;

namespace Tickets.Model
{

	[Serializable]
	public class Project
	{

		private int id = default( int );
		private string code;
		private string description;
		private IList<Ticket> tickets = new List<Ticket>();

		protected Project()
		{
		}

		public Project( string code, string description )
		{
			Code = code;
			Description = description;
		}

		public int Id
		{
			get { return id; }
		}

		public string Code
		{
			get { return code; }
			set { code = value; }
		}

		public string Description
		{
			get { return description; }
			set { description = value; }
		}

		#region Tickets
		public Ticket AddTicket( string ticketCode, string ticketText )
		{
			Ticket newTicket = new Ticket(this, ticketCode, ticketText);
			tickets.Add( newTicket );
			return newTicket;
		}

		public void RemoveTicketByCode( string ticketCode )
		{
			foreach ( Ticket ticket in tickets )
			{
				if ( ticket.Code.Trim().ToLower().Equals( ticketCode.Trim().ToLower() ) )
				{
					RemoveTicket( ticket );
					return;
				}
			}
		}

		public void RemoveTicket( Ticket ticket )
		{
			if ( ticket == null )
				throw new ArgumentNullException( "ticket", "Can't remove null ticket." );
			tickets.Remove( ticket );
		}

		public Ticket GetTicketById(int ticketId)
		{
			foreach (Ticket ticket in tickets)
				if (ticket.Id.Equals(ticketId))
					return ticket;
			return null;
		}

		public Ticket[] GetTicketsSortedByCode()
		{
			List<Ticket> tmpList = new List<Ticket>(tickets);
			tmpList.Sort(delegate(Ticket x, Ticket y)
											{
												if (x == null)
													throw new ArgumentNullException("x", "Can't compare null tickets.");
												if (y == null)
													throw new ArgumentNullException("y", "Can't compare null tickets.");
												return x.Code.CompareTo(y.Code);
											});
			return tmpList.ToArray();
		}
		#endregion

	}
}
